<template>
<div class="ivu-card ivu-card-bordered ivu-card-dis-hover" v-if="viewLoading">
  <div class="ivu-card-head"><p>{{ $route.meta.title }}</p></div>
  <div class="ivu-card-body">
    <iForm ref="formRef" :model="formModel" :rules="rules" :label-width="100">
      <FormItem prop="products_class_id" label="产品分类">
        <i-select v-model="formModel.products_class_id">
          <i-option v-for="vPC in productsClass" :value="vPC.products_class_id" :key="vPC.products_class_id">{{ vPC.name }}</i-option>
        </i-select>
      </FormItem>

      <FormItem prop="name" label="名称：">
        <Input v-model="formModel.name" placeholder="名称"/>
      </FormItem>

      <FormItem label="图片上传：">
        <Upload ref="uploadRef"
          :action="currentConfig.uploadAction"
          accept="image/*" :format="['jpg','jpeg','png']" :maxSize="2048"
          :on-success="onUploadSuccess"  :on-remove="onUploadRemove"
          :default-file-list="defaultUploadFileList"
        >
          <Button type="ghost" icon="ios-cloud-upload-outline">上传</Button>
        </Upload>
      </FormItem>

      <FormItem prop="price_rmb" label="人民币价格：">
        <Input v-model="formModel.price_rmb" placeholder="人民币价格"/>
      </FormItem>

      <FormItem prop="price_retail" label="零售积分价格：">
        <Input v-model="formModel.price_retail" placeholder="零售积分价格"/>
      </FormItem>

      <FormItem prop="price_shop" label="商城积分价格：">
        <Input v-model="formModel.price_shop" placeholder="商城积分价格"/>
      </FormItem>

      <FormItem prop="stock" label="库存：">
        <Input v-model="formModel.stock" placeholder="库存"/>
      </FormItem>

      <FormItem prop="details" label="产品详细：">
        <Input v-model="formModel.details" type="textarea" placeholder="产品详细"/>
      </FormItem>

      <FormItem prop="is_shelf" label="是否上架：">
        <i-select v-model="formModel.is_shelf">
          <i-option v-for="(vShelf, kShelf) in config['shop_is_shelf']" :value="kShelf" :key="kShelf">{{ vShelf }}</i-option>
        </i-select>
      </FormItem>

      <FormItem>
        <Button type="primary" :loading="submitLoading" @click="handleSubmit">修改</Button>
        <Button type="ghost" @click="$router.go(-1);">返回</Button>
      </FormItem>
    </iForm>
  </div>
</div>
</template>

<script>
import qs from 'qs';
import { Form, Input, Button, Select, Option, Upload, Message } from 'iview';
import config from '@/config';
import auth from '@/utils/auth';
import ajaxiView from '@/utils/ajaxiView';
import apiConfig from '@/utils/apiConfig';

export default {
  components: {
    [Form.name]: Form,
    [Form.Item.name]: Form.Item,
    [Input.name]: Input,
    [Button.name]: Button,
    [Select.name]: Select,
    [Option.name]: Option,
    [Upload.name]: Upload
  },
  data() {
    return {
      config: {},
      currentConfig: config,
      token: auth.getToken(),
      productsClass: {},
      defaultUploadFileList: [],
      formModel: {
        products_class_id: 0,
        name: '',
        images: [],
        price_rmb: 0,
        price_retail: 0,
        price_shop: 0,
        stock: 0,
        details: '',
        is_shelf: '1'
      },
      viewLoading: false,
      submitLoading: false,
      rules: {
        products_class_id: [
          {type:'string', required: true, message: '请选择产品分类!', trigger: 'blur'}
        ],
        name: [
          {type:'string', required: true, message: '产品名称不能为空!', trigger: 'blur'}
        ],
        is_shelf: [
          {type: 'string', required: true, message: '请选择是否上架!', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    handleSubmit() {
      var _this = this;
      _this.$refs.formRef.validate((valid) => {
        _this.submitLoading = true;

        if(valid) {
          ajaxiView.put('/products/'+_this.$route.params.products_id+'?token='+_this.token, qs.stringify(_this.formModel)).then(function(data) {
            if(data !== false) {
              Message.success({
                content: data.msg,
                onClose: function() {
                  _this.$router.push({ name: 'shopProductsIndex' });
                }
              });
            }
          });
        }

        _this.submitLoading = false;
      });
    },
    getProductsClass() {
      var _this = this;
      ajaxiView.get('/products/class?token='+_this.token+'&limit=9999').then(function(data) {
        if(data !== false) {
          _this.productsClass = data.pager.items;
        }
      });
    },
    onUploadSuccess(response, file, fileList) {
      if(response.code != 0) {
        Message.error(response.msg);
      }
      Message.success(response.msg);
      for(let k in response.files) {
        file.name = response.files[k];
      }
      this.formModel.images = [];
      for(let v in fileList) {
        this.formModel.images.push(fileList[v].name);
      }
    },
    onUploadRemove(file, fileList) {
      this.formModel.images = [];
      for(let v in fileList) {
        this.formModel.images.push(fileList[v].name);
      }
    }
  },
  mounted() {
    var _this = this;
    apiConfig.getItem().then(function(value) {
      _this.config = value;

      _this.getProductsClass();

      ajaxiView.get('/products/'+_this.$route.params.products_id+'?token='+_this.token).then(function(data) {
        if(data !== false) {
          for(var i in _this.formModel) {
            switch(i) {
              case 'images':
                  let images = JSON.parse(data.products.images);
                  _this.formModel.images = [];
                  for(let i in images) {
                    _this.formModel.images.push(images[i]);
                    _this.defaultUploadFileList.push({name: images[i], url: _this.currentConfig.uploadUrl+images[i]});
                  }
                break;
              default:
                _this.formModel[i] = data.products[i];
                break;
            }
          }
          _this.viewLoading = true;
        }
      });
    });
  }
}
</script>